<template>
  <!-- 移动端首页 -->
  <div class="mobile-home">
    <div class="mobile-header">
      <div class="title">
        <h2>北化浩绅管理平台</h2>
      </div>
      <div class="user-info">
        <el-dropdown trigger="click" @command="handleCommand">
          <span class="el-dropdown-link">
            <!-- <el-avatar :size="32" :src="avatar"></el-avatar> -->
            <span>{{ userInfo.nickName }}</span>
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <!-- <el-dropdown-item command="userInfo">个人信息</el-dropdown-item> -->
            <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <div class="mobile-content">
      <!-- 快捷功能区 -->
      <div class="quick-functions">
        <h3>快捷功能</h3>
        <div class="function-grid">
          <div class="function-item" v-for="(item, index) in quickFunctions" :key="index" @click="goToFunction(item)">
            <el-button type="primary" circle>
              <i :class="item.icon"></i>
            </el-button>
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>

      <!-- 待办事项区 -->
      <div class="to-do-list">
        <h3>待办事项</h3>

        <div v-if="todoList.length === 0" class="empty-list">
          <i class="el-icon-s-order"></i>
          <p>暂无待办事项</p>
        </div>
      </div>
    </div>

    <div class="mobile-footer">
      <p>北化浩绅管理平台 © 2025</p>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUserProfile } from '@/api/system/user'
import { mobileConfirm } from '@/utils/mobile'
import { isMobile } from '@/utils/device'
import { getToken } from '@/utils/auth'

export default {
  name: 'MobileHome',
  data() {
    return {
      avatar: '',
      userInfo: {
        userName: ''
      },
      quickFunctions: [
        { name: '用车登记', icon: 'el-icon-edit', path: '/mobile/useCar' },
        { name: '一键还车', icon: 'el-icon-s-cooperation', action: 'returnCar' },
        // { name: '生产管理', icon: 'el-icon-s-cooperation', path: '/mobile/production' },
        // { name: '库存管理', icon: 'el-icon-s-goods', path: '/mobile/inventory' },
        // { name: '质量检验', icon: 'el-icon-s-check', path: '/mobile/quality' },
        // { name: '数据报表', icon: 'el-icon-s-data', path: '/mobile/reports' },
        // { name: '系统设置', icon: 'el-icon-s-tools', path: '/mobile/settings' }
      ],
      todoList: []
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  beforeRouteEnter(to, from, next) {
    // 进入路由前检查是否为移动设备
    if (!isMobile()) {
      // 如果不是移动设备，重定向到桌面首页
      next('/');
    } else {
      next();
    }
  },
  created() {
    // 再次确认是移动设备
    if (!isMobile()) {
      this.$router.replace('/');
      return;
    }
    
    // 检查是否已登录
    if (!getToken()) {
      this.$router.replace('/login');
      return;
    }
    
    this.getUser()
    this.getTodoList()
  },
  methods: {
    getUser() {
      getUserProfile().then(res => {
        this.userInfo = res.data
        this.avatar = process.env.VUE_APP_BASE_API + this.userInfo.avatar
      })
    },
    handleCommand(command) {
      if (command === 'userInfo') {
        this.$router.push('/mobile/user/profile')
      } else if (command === 'logout') {
        mobileConfirm('确定注销并退出系统吗?', '提示').then(() => {
          // 彻底清除登录状态
          this.completeLogout()
        }).catch(() => {})
      }
    },
    completeLogout() {
      // 先调用后端登出接口
      this.$store.dispatch('LogOut')
        .then(() => {
          this.performLocalLogout()
        })
        .catch(() => {
          // 即使后端登出失败，也要强制前端登出
          this.$store.dispatch('FedLogOut')
          this.performLocalLogout()
        })
    },
    performLocalLogout() {
      // 清除所有cookie
      this.clearAllCookies()
      
      // 清除localStorage和sessionStorage
      localStorage.clear()
      sessionStorage.clear()
      
      // 清除Vuex状态
      this.$store.commit('SET_TOKEN', '')
      this.$store.commit('SET_ROLES', [])
      this.$store.commit('SET_PERMISSIONS', [])
      
      // 清除标签视图
      try {
        this.$store.dispatch('delAllViews')
      } catch (error) {
        console.error('清除视图失败', error)
      }
      
      // 使用replace而不是push，确保不能通过浏览器后退按钮回到已登出的页面
      window.location.replace('/login')
    },
    clearAllCookies() {
      const cookies = document.cookie.split(';')
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i]
        const eqPos = cookie.indexOf('=')
        const name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim()
        document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`
      }
    },
    goToFunction(item) {
      if (item.path) {
        this.$router.push(item.path)
      } else if (item.action === 'returnCar') {
        this.returnCar()
      }
    },
    getTodoList() {
      // 这里应该调用待办事项的API
      // 使用模拟数据
      this.todoList = [
        {
          id: 1,
          title: '待审批物料申请',
          content: '车间生产部门提交的原材料申请需要审核',
          status: '待处理',
          tagType: 'warning',
          time: '2023-05-20 10:30'
        },
        {
          id: 2,
          title: '质量检验任务',
          content: '有5批次产品需要进行质量检验',
          status: '紧急',
          tagType: 'danger',
          time: '2023-05-20 09:15'
        }
      ]
    },
    handleTodo(item) {
      // 处理待办事项
      this.$message({
        message: `正在处理: ${item.title}`,
        type: 'success'
      })
    },
    // 还车功能
    returnCar() {
      mobileConfirm('确定要结束当前用车？', '提示').then(() => {
        import('@/api/mes/life/lifeCarUsageRecord').then(module => {
          module.endUseLifeCarUsageRecord(this.userInfo.userName).then(res => {
            this.$message({
              message: '还车成功',
              type: 'success'
            })
          }).catch(error => {
            console.error('还车失败:', error)
/*             this.$message({
              message: '还车失败，您当前没有用车记录',
              type: 'error'
            }) */
          })
        })
      }).catch(() => {
        // 用户取消操作
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.mobile-home {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;

  .mobile-header {
    background-color: #409EFF;
    color: white;
    padding: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);

    .title {
      h2 {
        margin: 0;
        font-size: 18px;
      }
      p {
        margin: 5px 0 0;
        font-size: 12px;
        opacity: 0.8;
      }
    }

    .user-info {
      .el-dropdown-link {
        display: flex;
        align-items: center;
        color: white;
        cursor: pointer;

        span {
          margin: 0 5px;
        }
      }
    }
  }

  .mobile-content {
    flex: 1;
    padding: 15px;

    .quick-functions {
      margin-bottom: 20px;

      h3 {
        margin-bottom: 15px;
        font-size: 16px;
        color: #333;
      }

      .function-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-gap: 15px;

        .function-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          
          span {
            margin-top: 8px;
            font-size: 14px;
          }
        }
      }
    }

    .to-do-list {
      h3 {
        margin-bottom: 15px;
        font-size: 16px;
        color: #333;
      }

      .todo-item {
        margin-bottom: 15px;

        .el-card__header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 15px;
        }

        .todo-content {
          padding: 0 5px;

          p {
            margin-bottom: 10px;
            color: #666;
          }

          .todo-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .time {
              font-size: 12px;
              color: #999;
            }
          }
        }
      }

      .empty-list {
        text-align: center;
        padding: 30px 0;
        color: #909399;

        i {
          font-size: 40px;
          margin-bottom: 10px;
        }
      }
    }
  }

  .mobile-footer {
    text-align: center;
    padding: 15px;
    background-color: #f0f2f5;
    color: #606266;
    font-size: 12px;
  }
}
</style> 